package com.bj58.wuxian.lucene.demo;

import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.store.Directory;
import org.junit.Before;
import org.junit.Test;

import com.bj58.wuxian.lucene.constants.Constants;
import com.bj58.wuxian.lucene.utils.LuceneUtil;

public class IndexerAndSearcher {

	private Analyzer analyzer;
	private Directory directory;

	@Before
	public void init() throws IOException {
		analyzer = new StandardAnalyzer();

		// 在内存中 创建索引
		// directory = LuceneUtil.getRAMDirectory();
		// 在磁盘中创建索引
		directory = LuceneUtil.getDirectory(Constants.DIRECTROY_PATH);

	}

	// 创建索引
	@Test
	public void index() throws IOException {
		IndexWriter iwriter = LuceneUtil.getIndexWriter(directory, analyzer);
		Document doc = new Document();
		String text = "Lucene是apache软件基金会的一个子项目，是一个开放源代码的全文检索引擎工具包";
		doc.add(new Field("context", text, TextField.TYPE_STORED));
		iwriter.addDocument(doc);
		LuceneUtil.close(iwriter, directory);
	}

	// 搜索
	@Test
	public void search() throws IOException, ParseException {

		DirectoryReader reader = LuceneUtil.getDirectoryReader(directory);
		IndexSearcher isearcher = LuceneUtil.getIndexSearcher(reader);

		// 解析称为一个 "text":
		QueryParser parser = new QueryParser("context", analyzer);
		Query query = parser.parse("lucene");
		ScoreDoc[] hits = isearcher.search(query, 10).scoreDocs;

		for (int i = 0; i < hits.length; i++) {
			Document hitDoc = isearcher.doc(hits[i].doc);
			System.out.println(hitDoc.get("context"));
		}
		LuceneUtil.close(reader, directory);
	}
}
